package xyz.xiangyushui.controller.authentication;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import xyz.xiangyushui.daoFactory.user.UserDaoFactory;
import xyz.xiangyushui.javaBean.user.User;

/**
 * Servlet implementation class Auth
 */
@WebServlet("/Auth")
public class Auth extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private UserDaoFactory f;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public Auth() {
        super();
        f=new UserDaoFactory();
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.getWriter().append("Served at: ").append(request.getContextPath());
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String userName=request.getParameter("userName");
		String password=request.getParameter("password");
		User u=f.getUserDao().auth(userName, password);
		if(u==null){
			request.setAttribute("authFailed", "true");
			request.getRequestDispatcher("/login").forward(request, response);
		}else{
			request.getSession(true).setAttribute("user", u);
			request.getSession(true).setAttribute("userName", u.getName());
			request.getRequestDispatcher("/router").forward(request, response);
		}
	}

}
